package com.cold.demo.template.config;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

@Component
public class AppContext implements ApplicationContextAware, ServletContextAware {

    private static ApplicationContext applicationContext;
    private static ServletContext     servletContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        AppContext.applicationContext = applicationContext;
    }

    @Override
    public void setServletContext(ServletContext servletContext) {
        AppContext.servletContext = servletContext;
    }

    public static HttpServletRequest request() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }

    public static HttpServletResponse response() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getResponse();
    }

    public static ApplicationContext applicationContext() {
        return AppContext.applicationContext;
    }

    public static ServletContext servletContext() {
        return AppContext.servletContext;
    }


    public static Cookie getCookie(String cookieKey) {
        Cookie[] cookies = request().getCookies();
        for (Cookie cookie : cookies) {
            if (cookieKey.equals(cookie.getName())) {
                return cookie;
            }
        }
        return null;
    }

    public static void setCookie(Cookie cookie) {
        response().addCookie(cookie);
    }

}
